<template>
  <div class="profile-container">
    <!-- 顶部导航 -->
    <div class="profile-header">
      <el-icon class="back-btn" :size="24" @click="goBack">
        <ArrowLeft />
      </el-icon>
      <h1 class="page-title">个人资料</h1>
      <div class="header-actions">
        <el-button type="primary" size="small" @click="saveProfile" :loading="saving">
          保存
        </el-button>
      </div>
    </div>

    <!-- 个人信息编辑 -->
    <div class="profile-content">
      <!-- 头像上传区域 -->
      <div class="avatar-section">
        <h3 class="section-title">头像设置</h3>
        <AvatarUpload
          :user-id="userStore.userId"
          :avatar-url="userStore.userInfo?.avatar"
          size="extra-large"
          :editable="true"
          :show-actions="true"
          @avatar-updated="onAvatarUpdated"
          @upload-start="onUploadStart"
          @upload-success="onUploadSuccess"
          @upload-error="onUploadError"
        />
      </div>

      <!-- 基本信息 -->
      <div class="info-section">
        <h3 class="section-title">基本信息</h3>
        
        <el-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileRules"
          label-width="80px"
          class="profile-form"
        >
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="profileForm.nickname"
              placeholder="请输入昵称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="profileForm.username"
              placeholder="请输入用户名"
              maxlength="20"
              :disabled="true"
            />
            <div class="form-tip">用户名不可修改</div>
          </el-form-item>

          <el-form-item label="个性签名" prop="signature">
            <el-input
              v-model="profileForm.signature"
              type="textarea"
              :rows="3"
              placeholder="写点什么介绍一下自己吧..."
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profileForm.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">保密</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="profileForm.birthday"
              type="date"
              placeholder="选择生日"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 账号统计 -->
      <div class="stats-section">
        <h3 class="section-title">账号统计</h3>
        
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-number">{{ userStats.videoCount }}</div>
            <div class="stat-label">发布视频</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-number">{{ userStats.likeCount }}</div>
            <div class="stat-label">获得点赞</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-number">{{ userStats.followCount }}</div>
            <div class="stat-label">关注数</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-number">{{ userStats.fanCount }}</div>
            <div class="stat-label">粉丝数</div>
          </div>
        </div>
      </div>

      <!-- 账号设置 -->
      <div class="settings-section">
        <h3 class="section-title">账号设置</h3>
        
        <div class="setting-item" @click="changePassword">
          <div class="setting-info">
            <div class="setting-title">修改密码</div>
            <div class="setting-desc">定期修改密码，保护账号安全</div>
          </div>
          <el-icon class="setting-arrow">
            <ArrowRight />
          </el-icon>
        </div>

        <div class="setting-item" @click="privacySettings">
          <div class="setting-info">
            <div class="setting-title">隐私设置</div>
            <div class="setting-desc">管理个人信息的可见性</div>
          </div>
          <el-icon class="setting-arrow">
            <ArrowRight />
          </el-icon>
        </div>

        <div class="setting-item danger" @click="logout">
          <div class="setting-info">
            <div class="setting-title">退出登录</div>
            <div class="setting-desc">退出当前账号</div>
          </div>
          <el-icon class="setting-arrow">
            <ArrowRight />
          </el-icon>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import AvatarUpload from '@/components/AvatarUpload/index.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const profileFormRef = ref(null)
const saving = ref(false)
const apiAvailable = ref(true) // 头像API是否可用

// 表单数据
const profileForm = reactive({
  nickname: '',
  username: '',
  signature: '',
  gender: 0,
  birthday: ''
})

// 表单验证规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 用户统计数据
const userStats = reactive({
  videoCount: 0,
  likeCount: 0,
  followCount: 0,
  fanCount: 0
})

// 初始化表单数据
const initFormData = () => {
  if (userStore.userInfo) {
    profileForm.nickname = userStore.userInfo.nickname || ''
    profileForm.username = userStore.userInfo.username || ''
    profileForm.signature = userStore.userInfo.signature || ''
    profileForm.gender = userStore.userInfo.gender || 0
    profileForm.birthday = userStore.userInfo.birthday || ''
  }
}

// 获取用户统计数据
const fetchUserStats = async () => {
  try {
    // 这里应该调用实际的API获取用户统计数据
    // const response = await getUserStats()
    // userStats.videoCount = response.data.videoCount
    // userStats.likeCount = response.data.likeCount
    // userStats.followCount = response.data.followCount
    // userStats.fanCount = response.data.fanCount
    
    // 模拟数据
    userStats.videoCount = 12
    userStats.likeCount = 1234
    userStats.followCount = 56
    userStats.fanCount = 789
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

// 保存个人资料
const saveProfile = async () => {
  try {
    const valid = await profileFormRef.value.validate()
    if (!valid) return

    saving.value = true

    // 这里应该调用实际的API更新用户信息
    // const response = await updateUserProfile(profileForm)
    
    // 模拟保存成功
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新本地用户信息
    if (userStore.userInfo) {
      Object.assign(userStore.userInfo, profileForm)
    }

    ElMessage.success('个人资料保存成功')
  } catch (error) {
    console.error('保存个人资料失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 头像更新回调
const onAvatarUpdated = (avatarUrl) => {
  console.log('头像更新成功:', avatarUrl)
  userStore.updateUserAvatar(avatarUrl)
}

const onUploadStart = () => {
  console.log('开始上传头像')
}

const onUploadSuccess = (data) => {
  console.log('头像上传成功:', data)
  ElMessage.success('头像更新成功')
}

const onUploadError = (error) => {
  console.error('头像上传失败:', error)
  
  // 只有在真正的服务器错误或网络错误时才提示API不可用
  if (error.response?.status === 401) {
    ElMessage.error('登录已过期，请重新登录')
    // 自动跳转到登录页
    setTimeout(() => {
      router.push('/login')
    }, 2000)
  } else if (error.response?.status >= 500) {
    ElMessage.error('服务器错误，请稍后重试')
  } else if (error.message?.includes('Network Error')) {
    ElMessage.error('网络连接失败，请检查网络')
  } else {
    ElMessage.error(error.message || '头像上传失败，请重试')
  }
}

// 检测API可用性
const checkApiAvailability = async () => {
  try {
    // 尝试调用头像API检测是否可用
    const response = await fetch('/api/user/avatar/current', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })
    
    // API正常响应（包括404，说明API存在但用户没有头像）
    if (response.status < 500) {
      apiAvailable.value = true
      console.log('头像API可用')
    } else {
      apiAvailable.value = false
      console.log('头像API服务器错误')
    }
  } catch (error) {
    // 网络错误等，标记API不可用
    console.log('API可用性检测失败，网络或服务器问题:', error.message)
    apiAvailable.value = false
  }
}

// 修改密码
const changePassword = () => {
  ElMessage.info('修改密码功能开发中...')
}

// 隐私设置
const privacySettings = () => {
  ElMessage.info('隐私设置功能开发中...')
}

// 退出登录
const logout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '确认退出',
      {
        type: 'warning'
      }
    )
    
    userStore.logout()
    router.push('/login')
    ElMessage.success('已退出登录')
  } catch (error) {
    // 用户取消
  }
}

// 返回上一页
const goBack = () => {
  if (window.history.length > 1) {
    router.go(-1)
  } else {
    router.push('/')
  }
}

// 组件挂载
onMounted(() => {
  initFormData()
  fetchUserStats()
  checkApiAvailability()
})
</script>

<style lang="scss" scoped>
.profile-container {
  width: 100vw;
  min-height: 100vh;
  background: $bg-light;
  overflow-x: hidden;
}

.profile-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: $text-white;
  border-bottom: 1px solid $border-light;
  
  .back-btn {
    cursor: pointer;
    color: $text-dark;
    transition: $transition-fast;
    
    &:hover {
      transform: translateX(-2px);
    }
  }
  
  .page-title {
    flex: 1;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
    color: $text-dark;
  }
  
  .header-actions {
    min-width: 60px;
    display: flex;
    justify-content: flex-end;
  }
}

.profile-content {
  padding: 16px;
  max-width: 600px;
  margin: 0 auto;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: $text-dark;
  margin: 0 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid $primary-color;
}

.avatar-section {
  background: $text-white;
  padding: 20px;
  border-radius: $border-radius;
  margin-bottom: 16px;
  text-align: center;
}

.info-section {
  background: $text-white;
  padding: 20px;
  border-radius: $border-radius;
  margin-bottom: 16px;
  
  .profile-form {
    .form-tip {
      font-size: 12px;
      color: $text-gray;
      margin-top: 4px;
    }
  }
}

.stats-section {
  background: $text-white;
  padding: 20px;
  border-radius: $border-radius;
  margin-bottom: 16px;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    
    .stat-item {
      text-align: center;
      padding: 16px;
      border-radius: $border-radius;
      background: $bg-light;
      
      .stat-number {
        font-size: 24px;
        font-weight: 600;
        color: $primary-color;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 12px;
        color: $text-gray;
      }
    }
  }
}

.settings-section {
  background: $text-white;
  padding: 20px;
  border-radius: $border-radius;
  
  .setting-item {
    display: flex;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid $border-light;
    cursor: pointer;
    transition: $transition-fast;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:hover {
      background: $bg-light;
      margin: 0 -20px;
      padding-left: 20px;
      padding-right: 20px;
    }
    
    &.danger {
      .setting-title {
        color: $error-color;
      }
    }
    
    .setting-info {
      flex: 1;
      
      .setting-title {
        font-size: 14px;
        font-weight: 500;
        color: $text-dark;
        margin-bottom: 4px;
      }
      
      .setting-desc {
        font-size: 12px;
        color: $text-gray;
      }
    }
    
    .setting-arrow {
      color: $text-gray;
      font-size: 16px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .profile-content {
    padding: 12px;
  }
  
  .stats-section .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    
    .stat-item {
      padding: 12px;
      
      .stat-number {
        font-size: 20px;
      }
    }
  }
  
  .info-section,
  .avatar-section,
  .settings-section {
    padding: 16px;
  }
}
</style> 